package com.zmn.oms.dubbo.impl.zmn.normal.orderstock;

import com.google.common.collect.Lists;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.oms.business.interfaces.work.OrderWorkListBService;
import com.zmn.oms.common.enums.EncryptFieldTypeEnum;
import com.zmn.oms.dubbo.dto.zmn.orderstock.MasterStockOrderDRO;
import com.zmn.oms.dubbo.interfaces.zmn.normal.orderstock.MasterStockRemoteService;
import com.zmn.oms.dubbo.utils.DubboConsts;
import com.zmn.oms.model.entity.work.OrderWorkQuery;
import com.zmn.base.oms.common.model.es.orderwork.EsOrderWork;
import com.zmn.oms.services.interfaces.orderencrypt.OrderEncryptService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 类描述：订单库存
 *
 * @author heciqi
 * @date 2020/05/08 16:14
 */
@Slf4j
@Service(loadbalance = "roundrobin", timeout = 10000, version = DubboConsts.INTERFACE_VERSION, validation = "false")
public class MasterStockRemoteServiceImpl implements MasterStockRemoteService {
	@Autowired
	OrderWorkListBService orderWorkListBService;

	@Autowired
	OrderEncryptService orderEncryptService;

	/**
	 * 按单号查询订单信息
	 *
	 * @param orderIds
	 * @return
	 */
	@Override
	public ResponseDTO<List<MasterStockOrderDRO>> listOrderWorkByOrderIds(List<Long> orderIds) {
		log.debug("MasterStockRemoteService#listOrderWorkByOrderIds 入参{}", orderIds);

		OrderWorkQuery query = new OrderWorkQuery();
		query.setOrderIdList(orderIds);
		query.setIncludes(Arrays.asList("id", "orderId", "status", "resultStatus", "provinceName", "cityName",
				"countyName", "contact.street", "contact.address", "contact.location"));
		query.setPageSize(1000);
		List<EsOrderWork> esOrderWorks = orderWorkListBService.listPageOrderWorkByQuery(query);
		if (CollectionUtil.isNullOrEmpty(esOrderWorks)) {
			return ResponseDTO.success(Collections.EMPTY_LIST);
		}
		// 解密地址
		orderEncryptService.batchDecryptEsOrderWork(esOrderWorks, EncryptFieldTypeEnum.USER_ADDRESS);

		List<MasterStockOrderDRO> list = Lists.newArrayListWithExpectedSize(esOrderWorks.size());
		for (EsOrderWork esOrderWork : esOrderWorks) {
			MasterStockOrderDRO masterStockOrderDRO = BeanMapper.map(esOrderWork, MasterStockOrderDRO.class);
			if (Objects.nonNull(esOrderWork.getContact())) {
				masterStockOrderDRO.setStreet(esOrderWork.getContact().getStreet());
				masterStockOrderDRO.setAddress(esOrderWork.getContact().getAddress());
				masterStockOrderDRO.setLocation(esOrderWork.getContact().getLocation());
			}
			list.add(masterStockOrderDRO);
		}

		log.debug("MasterStockRemoteService#listOrderWorkByOrderIds 出参{}", list);
		return ResponseDTO.success(list);
	}
}
